package com.hunktimes.wholesale.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import com.hunktimes.wholesale.App

object SP {
    val KEY_USER_NAME = "username"
    val KEY_TOKEN = "token"
    val KEY_USER_ID = "userId"
    val KEY_USER_PHONE = "userphone"
    val KEY_NICK_NAME = "nickName"
    val KEY_UUID = "uuid"

    val EMPTY_STR = ""

    private fun getSpref(): SharedPreferences {
        //note PreferenceManager 在 API 29 android Q 被标记为过时
//        return PreferenceManager.getDefaultSharedPreferences(App.get().applicationContext)
        return App.get().applicationContext.getSharedPreferences(
            "${App.get().applicationContext.packageName}.user",
            Context.MODE_PRIVATE
        )
    }

    fun getCookieSpref(): SharedPreferences {
        return App.get().applicationContext.getSharedPreferences("cookies", Context.MODE_PRIVATE)
    }

    private fun getString(key: String): String = getSpref().getString(key, EMPTY_STR)!!

    @SuppressLint("ApplySharedPref")
    fun logOut() {
        getSpref().edit().clear().commit()
    }

    fun getUserId() = getString(KEY_USER_ID)
    fun getUserName() = getString(KEY_USER_NAME)
    fun getUserPhone() = getString(KEY_USER_PHONE)

    fun getToken() = getString(KEY_TOKEN)

    fun getUUID() = getString(KEY_UUID)

    fun saveToken(token: String) {
        getSpref().edit().putString(KEY_TOKEN, token).apply()
    }

    fun saveUserPhone(phoneNum: String) {
        getSpref().edit().putString(KEY_USER_PHONE, phoneNum).apply()
    }

    fun saveUUID(uuid: String) {
        getSpref().edit().putString(KEY_UUID, uuid).apply()
    }

    fun saveUserInfo() {
        getSpref().edit()
            .apply()
    }

    /**
     * @return true : 已登录 false : 未登录
     */
    fun isLogin(): Boolean {
        return !(getToken().isBlank())
//        return true
    }


    val KEY_PROTOCOL_VERSION_CODE = "protocal_version_code"
    /**
     * 是否同意了 用户协议
     */
    fun hasAgreeProtocol() = getProtocolVersion() >= VersionUtil.getVersionCode().toLong()


    fun saveProtocolVersion() {
        val versionCode = VersionUtil.getVersionCode().toLong()
        getSpref().edit()
            .putLong(KEY_PROTOCOL_VERSION_CODE, versionCode)
            .apply()
    }

    fun getProtocolVersion(): Long {
        return getSpref().getLong(KEY_PROTOCOL_VERSION_CODE, -1L)
    }
}